/**
 * 
 * @author 490501
 * @version 1.0.0.a
 * @description
 * Hoved fila med funksjoner for profile charts, som brukes for å lage nye forbruksmønstre
 * Dependencies:
 *   Highcharts.js 2.3.2+
 *   Jquery 1.8.1+
 *   Jquery UI Core 1.8.23+
 *   Jquery UI Position 1.8.23+
 *   Jquery UI Widget 1.8.23+
 *   Jquery UI Mouse 1.8.23+ (Optional; only needed if using UI Draggable or UI Resizable)
 *   Jquery UI Draggable 1.8.23+ (Optional)
 *   Jquery UI Resizable 1.8.23+ (Optional)
 *   (også CSS thema from JqueryUI, hvilken som heslt, virker bare på utsikt av name box)
 *   (all things you can find here in jquery folder, samt med css profil)
 *
 */
//bigger opp chart for belysning profil
$(function() {
(function(Highcharts) {
    var addEvent = Highcharts.addEvent,
        each = Highcharts.each;
    //begrenser drag, slik at den ikke går ut av range
    function filterRange(newY) {
            dragMin = 0, //0%
            dragMax = 100; //100%
        if (newY < dragMin) {
            newY = dragMin;
        } else if (newY > dragMax) {
            newY = dragMax;
        }
        return newY;
    }
   
    Highcharts.Chart.prototype.callbacks.push(function(chart) {

        var container = chart.container,dragPoint, dragX, dragY, dragPlotX, dragPlotY;
        chart.redraw(); 
        addEvent(container, 'mousedown', function(e) {
            var hoverPoint = chart.hoverPoint,
                options = hoverPoint && hoverPoint.series.options;
            if (options.draggableX) {
                dragPoint = hoverPoint;
                dragX = e.pageX;
                dragPlotX = dragPoint.plotX;
            }
            if (options.draggableY) {
                dragPoint = hoverPoint;
                dragY = e.pageY;
                dragPlotY = dragPoint.plotY + (chart.plotHeight - (dragPoint.yBottom || chart.plotHeight));
            }
        });
        //event mousemove
        addEvent(container, 'mousemove', function(e) {
            if (dragPoint) {
                var deltaY = dragY - e.pageY,
                    deltaX = dragX - e.pageX,
                    newPlotX = dragPlotX - deltaX - dragPoint.series.xAxis.minPixelPadding,
                    newPlotY = chart.plotHeight - dragPlotY + deltaY,
                    newX = dragX === undefined ? dragPoint.x : dragPoint.series.xAxis.translate(newPlotX, true),
                    newY = dragY === undefined ? dragPoint.y : dragPoint.series.yAxis.translate(newPlotY, true),
                    series = dragPoint.series;

                newY = filterRange(newY);

                dragPoint.update([newX, newY], false);
                chart.tooltip.refresh(dragPoint);
                if (series.stackKey) {
                    chart.redraw();
                } else {
                    series.redraw();
                }
            }
        });
        //drop event
        function drop(e) {
            if (dragPoint) {
                var deltaX = dragX - e.pageX,
                    deltaY = dragY - e.pageY,
                    newPlotX = dragPlotX - deltaX - dragPoint.series.xAxis.minPixelPadding,
                    newPlotY = chart.plotHeight - dragPlotY + deltaY,
                    series = dragPoint.series,
                    newX = dragX === undefined ? dragPoint.x : dragPoint.series.xAxis.translate(newPlotX, true),
                    newY = dragY === undefined ? dragPoint.y : dragPoint.series.yAxis.translate(newPlotY, true);

                newY = filterRange(newY);
                dragPoint.firePointEvent('drop');
                dragPoint.update([newX, newY]);

                dragPoint = dragX = dragY = undefined;
            }
        }
        addEvent(document, 'mouseup', drop);
        addEvent(container, 'mouseleave', drop);
    });

    var colProto = Highcharts.seriesTypes.column.prototype,
        baseDrawTracker = colProto.drawTracker;

    colProto.drawTracker = function() {
        var series = this;
        baseDrawTracker.apply(series);

        each(series.points, function(point) {
            point.tracker.attr(point.shapeArgs.height < 3 ? {
                'stroke': 'black',
                'stroke-width': 2,
                'dashstyle': 'shortdot'
            } : {
                'stroke-width': 0
            });
        });
    };
})(Highcharts);

//lager nytt chart objekt
var chart = new Highcharts.Chart({

    chart: {
        renderTo: 'light_profile',
        animation: false,
        type: 'area' //ka slags chart vil vi ha, mulige verdier se på off webside
    },
    //24 timer i dogn
    xAxis: {
        categories: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '00']
    },
    //forbruk i prosenter fra total effekt
    yAxis: {
        min: 0,
        max: 100,
        title: {
            text: 'in % of total consumption'
        }
    },
    //
    plotOptions: {
        series: {
            cursor: 'ns-resize',
            point: {
                events: {
                    drop: function() {
                        $('#report').html(//for debugging bare
                        this.category + ' was set to ' + Highcharts.numberFormat(this.y, 0)+' % of total effect');
                    }
                }
            }
        },
        column: {
            stacking: 'normal'
        }
    },

    tooltip: {
        yDecimals: 0
    },
    title: {
        text: 'Hourly lighting consumption'
    },
    //sjøl data, som som vises på chart
    series: [{
        data: [50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50],
        draggableY: true,
        name: 'Hourly consumption %'}]
    });
    
    //aktiverer reset knappa
    $('#button_reset_lighting').click(function() {//returnerer tilbake til opprinelige verdier
        chart.series[0].setData([50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50]);
    });
    
    //aktiverer save as new profile knappa
    $('#button_save_lighting').click(function() {
        var result = chart.series[0].data;
        var s = '';
        for(i = 0; i<result.length; i++) {
            s = s + Highcharts.numberFormat(result[i].y, 0) + ',';
        }
        //objekt som skal sendes til tjener
        var profile = {
            type: 'lighting',//mulige verdier lighting eller equip,depends on profile 
            name: 'name',
            values: s
        }
        //aapner vindu for å legge til navn
        $(function() {
            $( "#dialog" ).dialog({
                modal:true,
                buttons: {
                    close: function() {
                        $( this ).dialog( "close" );
                    },
                    save: function() {
                        //sender ny profil til tjener som håndterer det
                        profile.name = $('#idTxtFldProfileNameBox').val(); //legger til navn
                            $.ajax({
                                type: 'POST',
                                async: true,
                                url: '/NotesForSystemUtvikling/AjaxHandler', //Her skriver URL til servlet som håndterer 
                                data: profile, //det som vi sender
                                dataType: 'html', //det som vi får tilbake (kind of data we will get)
                                success: function(data,textStatus) { //haandterer svar 
                                    $('#dialog').html("Profile saved successfully");
                                    chart.series[0].setData([50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50]);
                                },
                                error: function(data, textstatus){
                                    $('#dialog').html('ooops, something goes wrong');
                                }
                            });    
                            $('#dialog').dialog('option','buttons',[
                                {
                                    text: "close",
                                    click: function() {$(this).dialog("close");}
                                }
                            ]);
                    }
                }
            });
            var nameBoxForm = '<input type="text" id="idTxtFldProfileNameBox" maxlength="64"/>';
            $('#dialog').html(nameBoxForm);
	});
    });
});


//bigger opp chart for equipment profil
$(function(){

(function(Highcharts) {
    var addEvent = Highcharts.addEvent,
        each = Highcharts.each;
    //begrenser drag, slik at den ikke går ut av range
    function filterRange(newY) {
            dragMin = 0,
            dragMax = 100;
        if (newY < dragMin) {
            newY = dragMin;
        } else if (newY > dragMax) {
            newY = dragMax;
        }
        return newY;
    }
    Highcharts.Chart.prototype.callbacks.push(function(chart) {
        var container = chart.container,
            dragPoint, dragX, dragY, dragPlotX, dragPlotY;
        chart.redraw();
        addEvent(container, 'mousedown', function(e) {
            var hoverPoint = chart.hoverPoint,
                options = hoverPoint && hoverPoint.series.options;
            if (options.draggableX) {
                dragPoint = hoverPoint;

                dragX = e.pageX;
                dragPlotX = dragPoint.plotX;
            }

            if (options.draggableY) {
                dragPoint = hoverPoint;

                dragY = e.pageY;
                dragPlotY = dragPoint.plotY + (chart.plotHeight - (dragPoint.yBottom || chart.plotHeight));
            }
        });
        //mousemove event her
        addEvent(container, 'mousemove', function(e) {
            if (dragPoint) {
                var deltaY = dragY - e.pageY,
                    deltaX = dragX - e.pageX,
                    newPlotX = dragPlotX - deltaX - dragPoint.series.xAxis.minPixelPadding,
                    newPlotY = chart.plotHeight - dragPlotY + deltaY,
                    newX = dragX === undefined ? dragPoint.x : dragPoint.series.xAxis.translate(newPlotX, true),
                    newY = dragY === undefined ? dragPoint.y : dragPoint.series.yAxis.translate(newPlotY, true),
                    series = dragPoint.series;

                newY = filterRange(newY);

                dragPoint.update([newX, newY], false);
                chart.tooltip.refresh(dragPoint);
                if (series.stackKey) {
                    chart.redraw();
                } else {
                    series.redraw();
                }
            }
        });
        //mouse drop event her
        function drop(e) {
            if (dragPoint) {
                var deltaX = dragX - e.pageX,
                    deltaY = dragY - e.pageY,
                    newPlotX = dragPlotX - deltaX - dragPoint.series.xAxis.minPixelPadding,
                    newPlotY = chart.plotHeight - dragPlotY + deltaY,
                    series = dragPoint.series,
                    newX = dragX === undefined ? dragPoint.x : dragPoint.series.xAxis.translate(newPlotX, true),
                    newY = dragY === undefined ? dragPoint.y : dragPoint.series.yAxis.translate(newPlotY, true);

                newY = filterRange(newY);
                dragPoint.firePointEvent('drop');
                dragPoint.update([newX, newY]);

                dragPoint = dragX = dragY = undefined;
            }
        }
        addEvent(document, 'mouseup', drop);
        addEvent(container, 'mouseleave', drop);
    });

    var colProto = Highcharts.seriesTypes.column.prototype,
        baseDrawTracker = colProto.drawTracker;

    colProto.drawTracker = function() {
        var series = this;
        baseDrawTracker.apply(series);

        each(series.points, function(point) {
            point.tracker.attr(point.shapeArgs.height < 3 ? {
                'stroke': 'black',
                'stroke-width': 2,
                'dashstyle': 'shortdot'
            } : {
                'stroke-width': 0
            });
        });
    };
})(Highcharts);
//lager nytt chart objekt (se først highcharts api nøyaktig før du endrer noe her)
var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'equip_profile',
        animation: false,
        type: 'area'
    },
    xAxis: {
        categories: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '00']
    },
    yAxis: {
        min: 0,
        max: 100,
        title: {
            text: 'in % of total consumption'
        }
    },
    plotOptions: {
        series: {
            cursor: 'ns-resize',
            point: {
                events: {
                    drop: function() {
                        $('#report_equip').html(
                        this.category + ' was set to ' + Highcharts.numberFormat(this.y, 0)+' % of total effect');
                    }
                }
            }
        },
        column: {
            stacking: 'normal'
        }
    },

    tooltip: {
        yDecimals: 0
    },
    title: {
        text: 'Hourly equipment consumption'
    },
    //data som viser hvilken andel av total effekt brukes  i en gitt timen
    series: [{
        data: [50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50],
        draggableY: true,
        name: 'Hourly consumption %'}]
    });
    
    //aktiverer reset knappa
    $('#button_reset_equipment').click(function() {
        chart.series[0].setData([50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50]);
    });
    
    
    //aktiverer save as new profile knappa
    $('#button_save_equipment').click(function() {
        var result = chart.series[0].data;
        var s = '';
        for(i = 0; i<result.length; i++) {
            s = s + Highcharts.numberFormat(result[i].y, 0) + ',';
        }
        //objekt som skal sendes til tjener
        var profile = {
            type: 'equip',//mulige verdier lighting eller equip,depends on profile 
            name: 'name',
            values: s
        }
        //aapner vindu for å legge til navn
        $(function() {
            $( "#dialog" ).dialog({
                modal:true,
                buttons: {
                    close: function() {
                        $( this ).dialog( "close" );
                    },
                    save: function(){
                        //sender ny profil til tjener som håndterer det
                        profile.name = $('#idTxtFldProfileNameBox').val(); //legger til navn
                            $.ajax({
                                type: 'POST',
                                async: true,
                                url: '/NotesForSystemUtvikling/AjaxHandler', //Her skriver URL til servlet som håndterer 
                                data: profile, //det som vi sender
                                dataType: 'html', //det som vi får tilbake (kind of data we will get)
                                success: function(data,textStatus) { //haandterer svar 
                                    $('#dialog').html("Profile saved successfully");
                                    chart.series[0].setData([50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50]);
                                },
                                error: function(data, textstatus){
                                    $('#dialog').html('ooops, something goes wrong');
                                }
                            });
                            $('#dialog').dialog('option','buttons',[
                                {
                                    text: "close",
                                    click: function() {$(this).dialog("close");}
                                }
                            ]);
                    }
                }
            });
            var nameBoxForm = '<input type="text" id="idTxtFldProfileNameBox" maxlength="64"/>';
            $('#dialog').html(nameBoxForm);
	});
    });
});


